/*
 * JaCoLiB
 * Copyright (C) 2008 Alessandro Serra
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package it.gashale.jacolib.rpc;

import java.io.IOException;
import java.util.Collection;
import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import it.gashale.jacolib.core.EvalError;
import it.gashale.jacolib.core.JacolibError;
import it.gashale.jacolib.core.ParserError;
import it.gashale.jacolib.core.ProtocolError;
import it.gashale.jacolib.core.TargetError;
import it.gashale.jacolib.json.SerializationObjectInterface;
import it.gashale.jacolib.json.Serializer;

public class RPCResponse implements SerializationObjectInterface {
	protected Object result;
	protected Object err;
	
	public RPCResponse() {
		this.result=null;
		err=null;
	}
	public RPCResponse(Object result) {
		this.result=result;
		err=null;
	}
	
	public Object getResult() {
		return result;
	}
	public void setResult(Object obj) {
		result=obj;
	}
	public Object getErr() {
		return err;
	}
	public void setErr(String typ, String msg) {
		Vector<String> li=new Vector<String>();
		li.add(typ); li.add(msg);
		err=li;
	}
	public Object getResponse() throws JacolibError {
		Object res=null;
		if(err==null) {
			res=result;
		} else {
			try {
				JSONArray a=(JSONArray)err;
				String typename = a.getString(0);
				String msg=a.getString(1);
				if(typename.equals("target")) {
					throw new TargetError(msg);
				} else if(typename.equals("parser")) {
					throw new ParserError(msg);
				} else if(typename.equals("eval")) {
					throw new EvalError(msg);
				}
			} catch (JSONException e) {
				throw new ProtocolError(e.getMessage());
			}
		}
		return res;
	}
	
	public void readObject(Serializer serializer, JSONObject jsonobj) throws JSONException, IOException, InternalError {
		result=jsonobj.get("result");
		if(result==JSONObject.NULL) {
			result=null;
		}
		err=jsonobj.get("err");
		if(err==JSONObject.NULL) {
			err=null;
		}
	}

	public void writeObject(Serializer serializer, JSONObject jsonobj) throws JSONException, IOException {
		jsonobj.put("type", "rpc.response");
		jsonobj.put("result", serializer.object_to_json(result));
		jsonobj.put("err", serializer.object_to_json((Collection)err));
	}

}
